package yscmd

import (
	"context"
	"gitee.com/kmyss/gf-ex/yslog"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcmd"
)

const CMD_HELP = "help"

type CmdHelpBuilder struct {
	CommandBuilderCore
}

func (b *CmdHelpBuilder) SetFlag(builder IFlagBuilder, _ ...string) bool {
	return false
}

func (b *CmdHelpBuilder) Init(ctx context.Context) {
	b.CommandBuilderCore.Init(ctx)

	b.C.Run = b.run
	b.C.Use = CMD_HELP
	b.C.Short = "显示帮助信息"
}

func (b *CmdHelpBuilder) SetChildCommand(builder ICommandBuilder) bool {
	return false
}

func (b *CmdHelpBuilder) run(c *Command) {
	yslog.Debug("CmdHelpBuilder Run")
	args := gcmd.GetArgAll()
	cmdStr := ""
	for i, arg := range args {
		if arg == CMD_HELP {
			cmdStr = gcmd.GetArg(i + 1).String()
		}
	}
	if g.IsEmpty(cmdStr) {
		c.parent.ShowHelp()
	} else {

		cmd := c.parent.commands.Get(cmdStr)
		if !g.IsEmpty(cmd) {
			cmd.(*Command).ShowHelp()
		} else {
			yslog.Errorf("%s 命令不存在!", cmdStr)
			c.parent.ShowHelp()
		}
	}

}

func CmdHelp(ctx context.Context) *Command {
	b := CmdHelpBuilder{}
	b.Init(ctx)
	return b.Command()
}
